<?php 
namespace app\admin\controller;

use think\Exception;
use app\common\model\depart\DepartList;
use think\Db;
use app\common\controller\Log;
use app\common\controller\Tree;
use app\common\model\depart\DepartPost;
use app\common\model\user\Users;

class Depart extends Base
{
	/**
	 * 获取部门列表
	 * @return unknown
	 */
	public function index()
	{
		//获取部门列表
		$list = DepartList::where(['state' => 1])->order('id asc')->select()->toArray();
		foreach ($list as &$rows) {
			//获取该部门所有的子部门
			$child_id = $this->getAllChild($rows['id'],[$rows['id']]);
			$rows['user_num'] = Users::where(['state' => 1,'depart_id' => ['in',$child_id]])->count();
			$rows['user_num1'] = Users::where(['state' => 1,'depart_id' => $rows['id']])->count();
			$rows['open'] = true;
			$rows['show'] = true;
		}
		$tree = new Tree();
		$list = $tree->setTree($list);
		sort($list);
		$res = $this->getDepartTree($list);
		return jsonSuccess($res);
	}
	/**
	 * 设置无限极部门列表排序
	 * @param unknown $list
	 * @return unknown[]
	 */
	private function getDepartTree($list)
	{
		$is_add = 0;
		$arr_temp = [];
		foreach ($list as $k => $v) {
			if(!empty($v['child'])) {
				$is_add ++;
				$item = $v['child'];
				unset($v['child']);
				$arr_temp[] = $v;
				if(count($item)){
					foreach ($item as $key => $val) {
						$arr_temp[] = $val;
					}
				}
			}else{
				$arr_temp[] = $v;
			}
		}
		if($is_add)return $this->getDepartTree($arr_temp);
		return $arr_temp; 
	}
	
	/**
	 * 添加部门列表
	 * @throws Exception
	 * @return unknown
	 */
	public function addDepart()
	{
		//获取客户端传递的数据
		$data = $this->request->post('');
		Db::startTrans();
		try {
			//验证数据的合法性
			if(!$data['depart_name'])throw new Exception('请输入部门名称');
			if(!$data['depart_no'])throw new Exception('请输入部门编号');
			if(DepartList::where(['depart_no' => $data['depart_no'],'state' => 1])->value('id'))
				throw new Exception('部门编号已存在');
			$depart = DepartList::where(['id' => $data['parent_id'],'state' => 1])->find();
			if($data['parent_id'] && !$depart)
				throw new Exception('非法操作');
			$data['create_time'] = time();
			$data['update_time'] = time();
			if($data['parent_id'] && $depart) {
				$data['level'] = $depart['level'] + 1;
			}else{
				$data['level'] = 0;
			}
			DepartList::create($data);
			//添加日志
			Log::addLog(1, '添加部门【'.$data['depart_name'].'】');
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('添加成功');
	}

	/**
	 * 删除部门
	 * @throws Exception
	 * @return unknown
	 */
	public function deleteDepart()
	{
		$id = $this->request->post('id');
		Db::startTrans();
		try {
			$depart = DepartList::get($id);
			if(!$depart->state)throw new Exception('状态错误');
			$ids = $this->getAllChild($id);
			array_unshift($ids, (int)$id);
			//判断该部门下面是否存在员工
			$id_len = count($ids);
			$depart_arr = [];
			for($i = 0;$i < $id_len;$i ++) {
				$temp = [];
				for($x = 0 ;$x <= $i ;$x ++) {
					$temp[] = $ids[$x];
				}
				$depart_arr[] = json_encode($temp);
			}
			if(Users::where(['state' => ['neq',0],'depart_id' => ['in',$depart_arr]])->select()){
				throw new Exception('该部门下存在员工无法删除');
			}
			$names = DepartList::where(['id' => ['in',$ids]])->column('depart_name');
			//删除自己及下级部门
			DepartList::where(['id' => ['in',$ids]])->update(['state'=>0]);
			//添加日志
			foreach ($names as $rows) {
				Log::addLog(3, "删除部门【{$rows}】");
			}
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('删除成功');
	}
	/**
	 * 获取所有下级部门id
	 */
	public function getAllChild($id,$id_arr = [])
	{
		$where = ['state' => 1];
		$where['parent_id'] = is_array($id) ? ['in',$id] : $id;
		$arr_id = DepartList::where($where)-> column('id');
		if(count($arr_id)) {
			$id_arr = array_merge($id_arr,$arr_id);
			return $this->getAllChild($arr_id,$id_arr);
		}
		return $id_arr;
	}
	/**
	 * 获取所有上级部门ID
	 * @param int $id
	 * @param array $id_arr
	 * @return array
	 */
	public function getAllParent($id,$id_arr = [])
	{
		$where = ['state' => 1];
		$where['id'] = is_array($id) ? ['in',$id] : $id;
		//dump($where);
		$arr_id = DepartList::where($where)-> column('parent_id');
		if(count($arr_id) && $arr_id[0]) {
			$id_arr = array_merge($id_arr,$arr_id);
			return $this->getAllParent($arr_id,$id_arr);
		}
		return $id_arr;
	}
	/**
	 * 获取部门信息
	 * @return unknown
	 */
	public function getDepartInfo()
	{
		$id = $this->request->post('id');
		try {
			$depart = DepartList::get($id);
			$depart->parent_name = $depart->parent_id ? DepartList::where(['id' => $depart->parent_id])->value('depart_name') : '顶级部门';
		} catch (Exception $e) {
			return jsonError($e->getMessage());
		}
		return jsonSuccess($depart);
	}
	
	/**
	 * 修改部门
	 * @throws Exception
	 * @return unknown
	 */
	public function editDepart()
	{
		$data = $this->request->post('');
		Db::startTrans();
		try {
			//验证数据的合法性
			if(!$data['depart_name'])throw new Exception('请输入部门名称');
			if(!$data['depart_no'])throw new Exception('请输入部门编号');
			$id = DepartList::where(['depart_no' => $data['depart_no'],'state' => 1])->value('id');
			if($id != $data['id'])
				throw new Exception('部门编号已存在');
			$depart = DepartList::where(['id' => $data['parent_id'],'state' => 1])->find();
			if($data['parent_id'] && !$depart)
				throw new Exception('非法操作');
			$data['update_time'] = time();
			DepartList::where(['id' => $data['id']])->update($data);
			//添加日志
			Log::addLog(2, '修改部门【'.$data['depart_name'].'】');
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('修改成功');
	}

	/**
	 * 职位列表
	 * @return unknown
	 */
	public function departList()
	{
		$list = DepartPost::where(['state' => 1])->select();
		return jsonSuccess($list);
	}
	/**
	 * 添加职位
	 * @throws Exception
	 * @return unknown
	 */
	public function addPost()
	{
		$post_name = $this->request->post('post_name');
		Db::startTrans();
		try {
			if(!$post_name)throw new Exception('请输入职位名称');
			if(DepartPost::where(['post_name' => $post_name,'state' => 1])->find())
				throw new  Exception('职位已存在');
			$data = [
					'post_name' => $post_name,
					'create_time'=> time(),
					'update_time' => time()
			];
			DepartPost::create($data);
			//添加日志
			Log::addLog(1, "添加职位【{$post_name}】");
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('添加成功');
	}

	/**
	 * 修改职位
	 * @throws Exception
	 * @return unknown
	 */
	public function editPost()
	{
		$data = $this->request->post('');
		Db::startTrans();
		try {
			$post_name = $data['post_name'];
			if(!$post_name)throw new Exception('请输入职位名称');
			$post = DepartPost::where(['post_name' => $post_name,'state' => 1])->value('post_name');
			if($post && $post != $post_name)
				throw new  Exception('职位已存在');
			DepartPost::get($data['id'])->save($data);
			//添加日志
			Log::addLog(2, "修改职位【{$post_name}】");
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('修改成功');
	}
	
	/**
	 * 删除职位
	 * @return unknown
	 */
	public function deletePost()
	{
		$id = $this->request->post('id');
		Db::startTrans();
		try {
			//判断该职位是否存在员工
			if(Users::where(['state' => ['neq',0],'post_id' =>$id])->find()){
				throw new Exception('该职位存在员工无法删除');
			}
			$post = DepartPost::get($id);
			$post -> save(['state' => 0]);
			//添加日志
			Log::addLog(3, "删除职位【{$post->post_name}】");
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('删除成功');
	}
}